package cn.sycoder.utils;

import cn.sycoder.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;  
import java.io.IOException;  
  
public class JsonUtil {  
  
    private static final ObjectMapper objectMapper = new ObjectMapper();  
  
    // Object 转 JSON 字符串  
    public static String objectToJson(Object obj) {  
        try {  
            return objectMapper.writeValueAsString(obj);  
        } catch (JsonProcessingException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
  
    // JSON 字符串 转 Object  
    public static <T> T jsonToObject(String jsonString, Class<T> clazz) {  
        try {  
            return objectMapper.readValue(jsonString, clazz);  
        } catch (IOException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }

    // 测试
//    public static void main(String[] args) {
//        User user = new User();
//        user.setUserName("杨润发");
//        String s = objectToJson(user);
//        System.out.println(s);
//
//        System.out.println(jsonToObject(s, User.class));
//    }
}